package com.fdhwws.web.servlet.api;

import com.fdhwws.web.domain.ChatRoom;
import com.fdhwws.web.domain.User;
import com.fdhwws.web.domain.UserFootprints;
import com.fdhwws.web.entity.AjaxResult;
import com.fdhwws.web.service.ChatRoomService;
import com.fdhwws.web.service.UserFootprintsService;
import com.fdhwws.web.service.impl.ChatRoomServiceImpl;
import com.fdhwws.web.service.impl.UserFootprintsServiceImpl;
import com.fdhwws.web.servlet.BaseServlet;
import jakarta.servlet.annotation.WebServlet;

import java.util.ArrayList;
import java.util.List;

@WebServlet(urlPatterns = "/api/user_footprints/*")
public class UserFootprintsAPIServlet extends BaseServlet {
    private final UserFootprintsService userFootprintsService = new UserFootprintsServiceImpl();
    private final ChatRoomService chatRoomService = new ChatRoomServiceImpl();

    public AjaxResult getUserFootprintsByUid_orderByTime(HttpUtil httpUtil) throws Exception {
        AjaxResult ajaxResult = verifyUser(httpUtil);
        if (!ajaxResult.isSuccess()) {
            return ajaxResult;
        }
        try {
            User user = (User) ajaxResult.data;
            AjaxResult queryAjaxResult = userFootprintsService.findAllUserFootprintsByUid_orderByTime(user.getId());
            if (queryAjaxResult.isSuccess()) {
                List<UserFootprints> list = (List<UserFootprints>) queryAjaxResult.data;
                List<ChatRoom> footprintChatRooms = new ArrayList<>();
                for (UserFootprints userFootprints : list) {
                    AjaxResult chatRoomByRoomIdAjaxResult = chatRoomService.getChatRoomByRoomId(userFootprints.getRoomId());
                    if (chatRoomByRoomIdAjaxResult.isSuccess()) {
                        ChatRoom data = (ChatRoom) chatRoomByRoomIdAjaxResult.data;
                        if (data.getValid()) {
                            footprintChatRooms.add(data.safeMode(false));
                        }
                    }
                }
                return AjaxResult.success("获取足迹成功", footprintChatRooms);
            } else {
                return queryAjaxResult;
            }
        } catch (NumberFormatException e) {
            return AjaxResult.error("uid异常", null);
        }
    }
}
